<?php

namespace app\common\model;

use org\util\HelpUtil;
use think\facade\Session;
use think\facade\Validate;
use think\model\concern\SoftDelete;

class TradeModel extends BaseModel {
    protected $name = 'trade';
    protected $pk = 'id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    //视图查询
    public function searchViewAttr($query, $value, $data) {

    }


    /**
     * 添加行业站点
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addData($data) {
        self::startTrans();
        try {
            $info = self::create($data);
            /*创建行业管理员*/
            $adminModel = new AdminModel();
            $adminData =[
                'username'=>$data['username'],
                'password'=>$data['password'],
                'nickname'=>$data['nickname'],
                'is_init'=>1
            ];
            $adminInfo = $adminModel->addData($adminData);
            /*创建行业顶级部门*/
            $deptModel = new DeptModel();
            $deptData =[
                'pid'=>0,
                'name'=>$data['trade_name'],
                'site_id'=>0,
                'trade_id'=>$info['id']
            ];
            $deptInfo = $deptModel->addData($deptData);
            /*创建商品类目顶级*/
            /*创建文章类目顶级*/
            /*反写admin_id,dept_id,trade_id到权限表*/
            AdminAccessModel::create([
                'admin_id'=>$adminInfo['id'],
                'site_id'=>0,
                'dept_id'=>$deptInfo['id'],
                'group_id'=>1,//暂时给与超管权限
                'trade_id'=>$info['id']
            ]);
            /*反写admin_id,dept_id到行业表*/
            $this->save([
                'dept_id'=>$deptInfo['id'],
                'admin_id'=>$adminInfo['id'],
            ],['id'=>$info['id']]);
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            exception($e->getMessage());
        }
        return true;
    }

    /**
     * 修改行业站点
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editData($data) {
        self::startTrans();
        try {
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            exception($e->getMessage());
        }
        return true;
    }
}